package com.itheima.health.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.utils.SMSUtils;
import com.itheima.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 发送手机验证，并将验证码存入到Redis中
 * @author zhengjd
 * @date 2020/4/8 9:35
 */
@RestController
@RequestMapping("/validateCode")
public class validateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 接收手机号，生成验证码并发送给用户，将验证码存入到Redis中，以便之后进行验证
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        Jedis jedis = null;
        try {
            //1.生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //2.调用工具发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            //3.将验证码存到Redis中,预留时间为60秒
            jedis = jedisPool.getResource();
            jedis.setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,5*60,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * 快速登录接收手机验证码
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        Jedis jedis = null;
        try {
            //1.生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //2.调用工具发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            System.out.println("登录手机验证码："+code);
            //3.将验证码存到Redis中,预留时间为60秒
            jedis = jedisPool.getResource();
            jedis.setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,5*60,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}
